/* The dialog.js is independent and need polish some how later */
/* The implementation need some convention in html design, so just internal use only */
/* The implementation does not use css path to find elements, it depends on the function getElementById */

/* The following tiny functions only take care of the display attribut */

var hint_addservice_title = "<a></a><h2>PUBLISH</h2>";
var hint_register_title = "<a></a><h2>REGISTER</h2>";
var hint_login_title = "<a></a><h2>LOGIN</h2>";
var hint_addservice_succ = "<a/><h2>Your Service Has Been Published</h2>";
var hint_error = "<a></a><h2>Some Error Occurred</h2>";
var hint_addgirl = "<a></a><h2>Add Girl</h2>";
var TimeStep = function(){
}
var zoyoe = new function(){
  this.InitZoyoe = function(){
  }
  this.has_right_dock = false; /* Only This Kind Of Variables Are Public */
  this.debug = false;
  //this.debug = true;
  this.refresh = false;
  this.submit_cb = null;
  this.comps = {};
  this.map = null;
  this.dock_style = 'ICON';
  this.week_day = new function(){
    this.Monday=0;
    this.Tuesday=1;
    this.Wednesday=2;
    this.Thursday=3;
    this.Friday=4;
    this.Saturday=5;
    this.Sunday=6;
  }
  this.content_active = true;
  this.ALERT = function(str){
    if (this.debug){
      alert(str);
    }
  }
  this.Update = function(update){
    var self = this;
    var config = {
        method: 'GET',
    }
    YUI().use("io-form",function(Y){
      function complete(id,o,args){
        zoyoe.ALERT(o.responseText);
        document.getElementById(args[0]).parentNode.innerHTML = o.responseText;
      }
      Y.on('io:complete',complete,Y,[update.comp_id]);
      var request = Y.io(update.uri,config);
    });
  }
  this.GeneralDialogInPanel = function (uri,config,cb){
    /* You must make sure the pannel is showd before calling this */
    YUI().use("io-form",function(Y){
      function complete(id,o,args){
        zoyoe.ALERT(o.responseText);
        YUI().use('node',function(yui_node){
          var panel = yui_node.one('#panel .panel-content');
          panel.set('innerHTML',o.responseText);
        });
      }
      Y.on('io:complete',complete);
      var request = Y.io(uri,config);
   });
  } 
  /* This is used to handle result 
  which is not triggered by a info_collect dialog*/
  this.GeneralDialog = function(uri,config,refresh,info){
    this.ShowDialog('Processing',true);
    YUI().use("io-form",function(Y){
      function complete(id,o,args){
        zoyoe.ALERT(o.responseText);
        var data = o.responseXML;
        if(data){
          if(data.documentElement.tagName == 'SUCC'){
            var msg = data.documentElement.getElementsByTagName('HTMLMSG')[0].firstChild.data;
            BuildGeneralMsg(msg,null);
            zoyoe.refresh = true;
            zoyoe.update = info;
          }else{ /* An Error has occurred */
            var msg = data.documentElement.getElementsByTagName('HTMLMSG')[0].firstChild.data;
            var errors = data.documentElement.getElementsByTagName('ERROR');
           if(errors.length > 0 ){
              var fst_error = errors[0].firstChild.data;
              msg = msg+fst_error;
              BuildGeneralMsg(msg,null,fst_error);
            }else{
             BuildGeneralMsg(msg);
            }
          }
        }else{
           BuildGeneralMsg(o.responseText);
        }
      }
      Y.on('io:complete',complete);
      var request = Y.io(uri,config);
    });
  }
  /* This is used to handle the result of a info_colloect dialog */
  this.GeneralDialogCont = function(uri,config,refresh,info){
    YUI().use("io-form",function(Y){
      function complete(id,o,args){
        var data = o.responseXML;
        zoyoe.ALERT(o.responseText);
        if(data.documentElement.tagName == 'SUCC'){
          var msg = data.documentElement.getElementsByTagName('HTMLMSG')[0].firstChild.data;
          BuildGeneralMsg(msg,null);
          zoyoe.refresh = true;
          zoyoe.update = info;
        }else{ /* An Error has occurred */
          var errors = data.documentElement.getElementsByTagName('ERROR');
          if(errors.length > 0 ){
            var fst_error = errors[0].firstChild.data;
            zoyoe.ALERT(fst_error);
            BuildErrorMsg(fst_error);
          }
          else{
            BuildErrorMsg('UNKOW ERROR!!');
          }
          YUI().use('node',function(node){
            var error_nodes = node.all('#' + zoyoe.dialog_name + ' .input-error');
            error_nodes.replaceClass('input-error','input-fine');
            for (var i=0;i<errors.length;i++){
              var name = errors[i].getAttribute('name');
              var path = "#" + zoyoe.dialog_name + " #"+name+' .input-fine';
              var anode = node.one(path);
              if(anode){
                anode.replaceClass('input-fine','input-error');
              } 
            }
          }); 
        }
      }
      Y.on('io:complete',complete);
      var request = Y.io(uri,config);
    });
  }
  this.InfoCollectDialog = function(h,uri,dialog_name,submit_callback){
    this.ShowDialog(h,true);
    this.submit_cb = submit_callback;
    this.dialog_name = dialog_name;
    YUI().use("io-form",function(Y){
      function complete(io,o,args){
        var msg = o.responseText+" ";
        var d = Y.one('#dialog .dialog-content');
        var dele = Y.Node.getDOMNode(d);
        dele.innerHTML = msg;
        if(zoyoe.ElementExtension){
          alert("Extension Elements");
          zoyoe.ElementExtension.BuildExtensionElements(d);
        }
      } 
      Y.on('io:complete',complete,Y);
      var request = Y.io(uri);
    });
  }
  this.IframeDialog = function(h,uri,dialog_name,submit_callback){
    this.ShowDialog(h,true);
    this.submit_cb = submit_callback;
    this.dialog_name = dialog_name;
    YUI().use("node",function(Y){
      var dialog = Y.one('#dialog .dialog-content');
      var ht = "<iframe frameborder='0' id='"+dialog_name + "' src = '"+uri+"'></iframe>"
      dialog.set('innerHTML',ht);
    });
  }
  this.ShowShortCut = function(pos,slist){
    var float_info = document.getElementById('float-info');
    float_info.style.left = n2px(pos.x - 107);
    float_info.style.top = n2px(pos.y + 5);
    if(this.content_active){
      this.HibernateContent();
      var count = 1;
      YUI().use('node',function(yui_node){
        for(var i=0;i<slist.length&&count<=4;i++){
          var serv = slist[i];
          var name = serv.name; 
          var img_src = "/adult/core/data/res/" + name + "/icon/?sc=mid";
          var img_cont = yui_node.one("#float-info div.left div.img"+count);
          img_cont.set('innerHTML',"<img src = '" + img_src +"' ></img>");
          count++;
        }
        for(var i=count;i<=4;i++){
          var img_cont = yui_node.one("#float-info div.left div.img"+i);
          img_cont.set('innerHTML',"");
        } 
        yui_node.one("#float-info .name").set('innerHTML',serv.name);
        yui_node.one("#float-info .phone").set('innerHTML',serv.phone);
        yui_node.one("#float-info .email").set('innerHTML',serv.email);
        yui_node.one("#float-info .address").set('innerHTML',serv.address);
        yui_node.one("#float-info .description").set('innerHTML',serv.description);
        yui_node.one("#float-info .nest span").set('innerHTML',slist.length);
        float_info.style.display = "block";
      });
    }
  }
  this.CloseShortCut = function(){
    var float_info = document.getElementById('float-info');
    float_info.style.display = "none";
    this.ActivateContent();
  }
  this.HideShortCut = function(){
    this.ActivateContent();
    YUI().use('node',function(yui_node){
      var float_info = node.one("#float-info");
      alert("float_find");
    });
  }
  this.HibernateContent = function HibernateContent(no_opacity){
    var mask = document.getElementById('zsk');
    /* We will not check the existance of the mask, 
    since we can not handle the problem once the convention is not applied */
    if(no_opacity){
      mask.className = 'msk_nop';
    }else{
      mask.className = 'msk';
    }
    mask.style.display = 'block';
    this.content_active = false;
  }
  this.ActivateContent = function(){
    var mask = document.getElementById('zsk');
    mask.style.display = 'none';
    document.body.style.overflow = "";
    this.content_active = true;
  }
  this.HideDialog = function(){
    YUI().use('node',function(yui_node){
      var dialog = yui_node.one('#dialog .dialog-content');
      var hint = yui_node.one('#dialog .dialog-hint');
      dialog.set('innerHTML',"");
      hint.set('innerHTML',"");
      yui_node.one('#dialog').setStyle('display','none');
    });
    this.ActivateContent();
  }
  this.ShowDialog = function(dialog_name,loading){
    this.HibernateContent();
    YUI().use('node',function(yui_node){
      var hint = yui_node.one('#dialog .dialog-hint');
      var ghint = "<a></a><h2>" + dialog_name + "</h2>";
      hint.set('innerHTML',ghint);
      yui_node.one('#dialog').setStyle('display','block');
      if(loading){
        var dialog = yui_node.one('#dialog .dialog-content');
        dialog.set('innerHTML',"<div class='loading'></div>");
      }
    });
  }
  this.ShowPanel = function(panel_name,service_name,gname){
    this.HibernateContent();
    YUI().use('node',function(yui_node){
      var panel = yui_node.one('#panel .panel-content');
      var hint = yui_node.one('#panel .panel-hint');
      if(panel_name = 'photo'){
        YUI().use("io-form",function(Y){
          uri = "/adult/core/dialog/"+service_name+"/gallery/";
          function complete(io,o,args){
            var icon_containers = yui_node.all('#panel .gicon')
            var gs = o.responseXML.getElementsByTagName('G');
            var g = null;
            var name = args[0];
            for (var i=0;i<gs.length;i++){
              if(gs[i].getAttribute('name') == name){
                g = gs[i];
              }
            }
            if(g == null){return;}
            else{
                var urls = g.getElementsByTagName('IMG'); 
                var gname = g.getAttribute('name');
                var prefix = "/adult/core/data/res/"+service_name+"/"+gname;
                var idx = 0;
                var name_list = [];
                for(;idx<7&&idx<urls.length;idx++){
                  var name = urls[idx].getAttribute('name');
                  var tstamp = "";
                  if(zoyoe && zoyoe.timestamp){
                    tstamp = "&tstamp="+zoyoe.timestamp;
                  }
                  icon_containers.item(idx).set('innerHTML',
                    "<img src='"
                    +prefix + '/' + name + "/?sc=small" + tstamp + "'></img>");
                  name_list.push(name);
                }
                for(var i = idx;i<7;i++){
                  icon_containers.item(i).set('innerHTML','');
                }
                zoyoe.comps['GALLERY'].ManageGallery(gname,name_list,function(innerHTML){
                  panel.set('innerHTML',innerHTML);
                });
              }
            }
           /*panel.set('innerHTML',o.responseText)*/
           Y.on('io:complete',complete,Y,[gname]);
           var request = Y.io(uri);
          });
        var d_hint = "<a class='gbutton' onclick=\"zoyoe.HidePanel();zoyoe.comps['GALLERY'].DelGallery('"+ gname + "')\">delete this gallery</a>"
       var c_hint = "<a class='gbutton' onclick=\"zoyoe.comps['GALLERY'].AddImg()\">upload new image</a>"
       var m_hint = "<a class='gbutton' onclick=\"zoyoe.comps['GALLERY'].ModifyImg()\">change current image</a>"
       var ghint = "<a class='gbutton' onclick='zoyoe.HidePanel()'>&#9746</a>" + d_hint + m_hint + c_hint + "<h2>Gallery:"+gname+"</h2>"
        hint.set('innerHTML',ghint);
      }else{
        var ghint = "<a></a><h2>" + dialog_name + "</h2>";
        hint.set('innerHTML',ghint);
      } 
     yui_node.one('#panel').setStyle('display','block');
    });
  }
  this.HidePanel = function(){
    YUI().use('node',function(yui_node){
      var dialog = yui_node.one('#panel .panel-content');
      dialog.set('innerHTML',"");
      yui_node.one('#panel').setStyle('display','none');
    });
    this.ActivateContent();
  }
  this.SwitchDockStyle = function(style){
    this.dock_style = style;
    if(this.map){
	    var this_map= this.map.map;
	    var core = this.map;
      var fa = GetMapArea();
      var groups = core.GetServicesInSquare(fa.left,fa.top,fa.width,fa.height);
      RefreshServicesInRightDock(groups);
    }
  }
}

YUI().use('async-queue','stylesheet',function(Y){
  zoyoe.async_queue = new Y.AsyncQueue(); 
  zoyoe.fade_list = new Array();
  zoyoe.stop_queue = function(){return false;}
  zoyoe.async_queue.add({
    fn:function(){
      if(zoyoe.fade_list.length ==0){
        zoyoe.async_queue.pause();
      }else{
        for(var i=0;i<zoyoe.fade_list.length;i++){
          var opacity = zoyoe.fade_list[i].getStyle('opacity') - 0.1; 
          zoyoe.fade_list[i].setStyle('opacity',opacity);
          if(opacity < 0.1){
            var n = zoyoe.fade_list[i];
            zoyoe.fade_list.splice(i,1);
            n.remove();
          }
        }
      }
    },timeout:50,until:zoyoe.stop_queue});
  zoyoe.async_queue.run();
});


function ResetShortCut(i){
  YUI().use('node',function(yui_node){
    var icon_containers = yui_node.all('#panel .gicon');
    var innerHTML = icon_containers.item(i).get('innerHTML');
    icon_containers.item(i).set('innerHTML','');
    icon_containers.item(i).set('innerHTML',innerHTML);
  });
}

function BuildGeneralMsg(msg,url,error_hint){
  YUI().use('node',function(yui_node){
    var title = yui_node.one('#dialog .dialog-hint h2');
    var hint = yui_node.one('#dialog .dialog-hint a');
    var dialog = yui_node.one('#dialog .dialog-content');
    if(error_hint){
      hint.set('innerHTML',error_hint);
    }
    dialog.set('innerHTML',"<div class='msg'>"+msg+"</div>");
    zoyoe.submit_cb = null;
  });
}
function BuildSuccMsg(msg,url){
  YUI().use('node',function(yui_node){
    var title = yui_node.one('#dialog .dialog-hint h2');
    var Generalhint = yui_node.one('#dialog .dialog-hint a');
    var dialog = yui_node.one('#dialog .dialog-content');
    dialog.set('innerHTML',msg);
    zoyoe.submit_cb = null;
  });
}

function BuildErrorMsg(msg,url){
  YUI().use('node',function(yui_node){
    var hint = yui_node.one('#dialog .dialog-hint a');
    var url = url;
    if(url == null){
      url = "";
    }
    hint.set('innerHTML',msg);
  });
}
  
/* The following function need YUI3 to succeed */

var add_service_uri = "/adult/core/data/addservice/";
var mdy_service_uri = "/adult/core/data/mdyservice/";
var register_uri = "/adult/core/user/register/";
var login_uri = "/adult/core/user/login/";
var logout_uri = "/adult/core/user/logout/";

function Reload(){
  if(document.forms['reload']){
    document.forms['reload'].submit();
  }else{
    zoyoe.ALERT('Try alternative Reload Function');
    location.reload(true);
  }
}

function Logout(){
  YUI().use("io-form",function(Y){
    uri = logout_uri;
    var logout_config = {
      method: 'GET',
    }
    function complete(id,o,args){
      Reload();
    }
    Y.on('io:complete',complete);
    var request = Y.io(logout_uri,logout_config);
  });
}

function Login(form_obj){
  YUI().use("io-form",function(Y){
    uri = login_uri;
    var login_config = {
      method: 'GET',
      form: {id:form_obj}
    }
    function complete(id,o,args){
      zoyoe.ALERT(o.responseText);
      var data = o.responseXML;
      if(data.documentElement.tagName == 'SUCC'){
        var msg = data.documentElement.getElementsByTagName('HTMLMSG')[0].firstChild.data;
        Reload();
      }else{ /* An Error has occurred */
         BuildErrorMsg('! Error, Login Failed');
      }
    }
    Y.on('io:complete',complete);
    var request = Y.io(login_uri,login_config);
  });
}

function Register(form_obj){
  if(form_obj.confirm.value != form_obj.password.value){
    BuildErrorMsg("! Password not confirmed.")
    return;
  }
  YUI().use("io-form",function(Y){
    uri = register_uri;
    var register_config = {
      method: 'GET',
      form: {id:form_obj}
    }
    function complete(id,o,args){
      zoyoe.ALERT(o.responseText);
      var data = o.responseXML;
      if(data.documentElement.tagName == 'SUCC'){
         var msg = data.documentElement.getElementsByTagName('HTMLMSG')[0].firstChild.data;
         BuildSuccMsg(msg);
      }else if(data.documentElement.tagName == 'CONFLICT'){
         /* A conflict has occured */
         var type = data.documentElement.getElementsByTagName('MSG')[0].firstChild.data;
         BuildErrorMsg(type);
      }else{ /* An Error has occurred */
         errors = data.documentElement.getElementsByTagName('ERROR');
         YUI().use('node',function(node){
           var error_nodes = node.all('.input-error');
           error_nodes.replaceClass('input-error','input-fine');
           /*zoyoe.ALERT(error_nodes);*/
           for (var i=0;i<errors.length;i++){
             var name = errors[i].getAttribute('name');
             var path = "#form-register #"+name+' .input-fine';
             var anode = node.one(path);
             if(anode){
               anode.replaceClass('input-fine','input-error');
             } 
           }
         }); 
         BuildErrorMsg('! Error, Invalid Inputs');
      }
    }
    Y.on('io:complete',complete);
    var request = Y.io(register_uri,register_config);
  });
}

/* The convention now is the map_component */
function ChangeIcon(){
}

function AddService(form_obj){
  var map_comp = zoyoe.map;/*Convention*/
  var script = document.createElement("script");
  script.setAttribute("type","text/javascript"); 
  script.setAttribute("src",map_comp.SearchUri(form_obj.address.value+',NSW,Australia')+"&jsonp=AddServiceJSON");
  document.body.appendChild(script);
}
function AddServiceJSON(result){
  var form_obj = document.getElementById(zoyoe.dialog_name);
  var days = new Array();
  if(result.resourceSets){
    if(result.resourceSets[0].estimatedTotal = 0){
      BuildErrorMsg('Address Not Found !!');
    }
    else if(result.resourceSets[0].estimatedTotal = 1){
      var resources = result.resourceSets[0].resources;
      if(resources.length == 0){
        BuildErrorMsg('Address Not Found !!');
      }else if(resources.length == 1){
        zoyoe.ALERT(resources[0].address.formattedAddress);
        form_obj.address.value = resources[0].address.formattedAddress; 
        if(form_obj.Sun.checked){days.push("Sun");}
        if(form_obj.Mon.checked){days.push("Mon");}
        if(form_obj.Tue.checked){days.push("Tue");}
        if(form_obj.Wed.checked){days.push("Wed");}
        if(form_obj.Thu.checked){days.push("Thu");}
        if(form_obj.Fri.checked){days.push("Fri");}
        if(form_obj.Sat.checked){days.push("Sat");}
        var c = resources[0].point.coordinates;
        zoyoe.ALERT(days.join(','));
        var add_service_config = {
          method: 'POST',
          data:'latitude='+c[0]+"&longitude="+c[1]+"&days="+days.join(','),
          form: {id:form_obj}
        }
        zoyoe.GeneralDialogCont(add_service_uri,add_service_config,true,null);
      }else{
        BuildErrorMsg('Ambiguious Address,Please Make It Clear !!');
      }
    }
    else{
      BuildErrorMsg('Multi Address Found,Please Make It Clear !!');
    }
  }
}

function ModifyService(form_obj){
  var days = new Array();
  if(form_obj.Sun.checked){days.push("Sun");}
  if(form_obj.Mon.checked){days.push("Mon");}
  if(form_obj.Tue.checked){days.push("Tue");}
  if(form_obj.Wed.checked){days.push("Wed");}
  if(form_obj.Thu.checked){days.push("Thu");}
  if(form_obj.Fri.checked){days.push("Fri");}
  if(form_obj.Sat.checked){days.push("Sat");}
  zoyoe.ALERT(days.join(','));
  var mdy_service_config = {
    method: 'POST',
    data:"&days="+days.join(','),
    form: {id:form_obj}
  }
  zoyoe.GeneralDialogCont(mdy_service_uri+zoyoe.service_name+"/",mdy_service_config,true,null);
}

function SubmitForm(){
  var form_obj = document.getElementById(zoyoe.dialog_name);
  if(form_obj!=null){
    if(zoyoe.submit_cb){
      zoyoe.submit_cb(form_obj);
    }
    /*
    if(dialog_form_name =='form-addservice'){
      AddService(form_obj);
    }else if(dialog_form_name == 'form-register'){
      Register(form_obj);
    }else if(dialog_form_name == 'form-login'){
      Login(form_obj);
    }else if(dialog_form_name == 'form-addroster'){
      zoyoe.comps['ROSTER'].AddRoster(form_obj);
    }else if(dialog_form_name == 'form-addgirl'){
      zoyoe.comps['GIRLS'].AddGirl(form_obj);
    }*/
    else{
       zoyoe.ActivateContent();
       zoyoe.HideDialog();
    } 
  }else{
    if(zoyoe.refresh){
      if(zoyoe.update){
        var config = {
          method: 'GET',
        }
        var p = document.getElementById(zoyoe.update.comp_id).parentNode;
        p.innerHTML = 'loading';
        YUI().use("io-form",function(Y){
          function complete(id,o,args){
            zoyoe.ALERT(o.responseText);
            p.innerHTML = o.responseText;
          }
          Y.on('io:complete',complete,Y,[p]);
          var request = Y.io(zoyoe.update.uri,config);
        });
        zoyoe.update = null;
      }else{
        location.reload(true); 
      }
    }
    zoyoe.ActivateContent();
    zoyoe.HideDialog();
  }
}
  var config = new function(){
     this.choice = new Array();
     this.combo = new Array();
     this.combo.push(new function(){
       this.name = "working-days";
       this.handler = function(type){
         zoyoe.map.ToggleWorkingDayFilter(type);
       }
     });
  }

function InitChoiceControl(setting){ 
   YUI().use('node',function(node){
     var values = node.all('#'+ setting.name + " a");
     values.on('click', function(e){
        values.removeClass('selected');
        e.currentTarget.addClass('selected');
        setting.handler(node.Node.getDOMNode(e.currentTarget.one('span')).nextSibling.data);
      });
   });
}

function InitComboControl(setting){ 
   YUI().use('node',function(node){
     var values = node.all('#'+ setting.name + " a");
     values.on('click', function(e){
        if(e.currentTarget.hasClass('selected')){
          e.currentTarget.removeClass('selected');
        }else{
          e.currentTarget.addClass('selected');
        }
        setting.handler(node.Node.getDOMNode(e.currentTarget.one('span')).nextSibling.data);
      });
   });
}

function InitSurburbList(){
   YUI().use('node',function(node){
     var scroll = node.one('#surburb div.div-scroll div.hscroll');
     var scroll_ele = node.Node.getDOMNode(scroll);
     MarkAsScrollH(scroll_ele);
     var values = node.all('div.surburb a');
     values.on('click', function(e){
       var ele = node.Node.getDOMNode(e.currentTarget);
       var address = ele.innerHTML;
       if(zoyoe.map){
         zoyoe.ALERT(address);
         zoyoe.map.TargetPlace(address,"TargetPlaceJSON");
       }
     });
     var values = node.all('div.vbar ul.surburb-list li')
     values.on('click', function(e){
       scroll_ele.Reset();
       var values = node.all('div.vbar ul.surburb-list li')
       values.removeClass('selected');
       e.currentTarget.addClass('selected');
       var ele = node.Node.getDOMNode(e.currentTarget);
       var idx = ele.innerHTML;
       if(zoyoe.surburb){
         var slist = zoyoe.surburb[idx];
         var n = node.one('#surburb div.div-scroll div.surburb');
         var ihtml = "";
         for(var i=0;i<slist.length;i++){
            ihtml += "<a>"+slist[i]+"</a>";
         }
         n.set('innerHTML',ihtml+"<br style='clear:both'></br>");
         var values = node.all('div.surburb a');
         values.on('click', function(e){
           var ele = node.Node.getDOMNode(e.currentTarget);
           var address = ele.innerHTML;
           if(zoyoe.map){
           zoyoe.ALERT(address);
           zoyoe.map.TargetPlace(address,"TargetPlaceJSON");
           }
         });
       }
     });
   });
}

function InitControlPanel(){
  YUI().use('dd-plugin', function(Y){
      var node = Y.one('#config-bar');
      node.plug(Y.Plugin.Drag);
      node.dd.addHandle('div.window-title');
  });
  for(var i=0;i<config.choice.length;i++){
    InitChoiceControl(config.choice[i]);
  }
  for(var i=0;i<config.combo.length;i++){
    InitComboControl(config.combo[i]);
  }
  InitSurburbList();
}
function GetMapArea(){
  return {left:0,top:0
  ,width:document.getElementById('map-info').offsetWidth
  ,height:document.getElementById('map-info').offsetHeight};
}
function ShowRightSideBar(){
  document.getElementById('right-bar').style.display = "block";
  document.getElementById('right-bar-dock').style.display = "block";
  document.getElementById('right-bar').style.left = n2px(document.getElementById('map-info').offsetWidth-230);
  document.getElementById('right-bar').style.height = n2px(document.getElementById('map-info').offsetHeight-35);
  document.getElementById('right-bar-dock').style.left = n2px(document.getElementById('map-info').offsetWidth-230);
  document.getElementById('right-bar-dock').style.height = n2px(document.getElementById('map-info').offsetHeight-35);
  zoyoe.has_right_dock = true;
}
function HideRightSideBar(){
  document.getElementById('right-bar').style.display = "none";
  document.getElementById('right-bar-dock').style.display = "none";
}

function ShowServiceInRightDock(service,style,main_tag){
  if(zoyoe.has_right_dock == false){return;/* Ugly Code make sure we have right dock */}
  YUI().use('node',function(node){
    n = node.one('#right-bar-dock');
    if(style == 'COMPACT' || !main_tag){
      var ndiv = node.Node.create(
        "<div class='cicon' onclick=\"window.location.href='/adult/core/service/"+service.name+"'\">"
        +"<img src='/adult/core/data/res/"+service.name+'/'+service.icon+"/?sc=true&cache=1' ></img>"
        +"</div>"
        );
      n.append(ndiv); 
      node.Node.getDOMNode(ndiv).service = service;
    }else{
      var gicon = node.one('#right-bar-dock div.lane div.icon');
      node.Node.getDOMNode(gicon).service = service;
      gicon.on('click',function(){
        window.location.href='/adult/core/service/'+service.name;
      });
      gicon.set('innerHTML',
        "<img src='/adult/core/data/res/"+service.name+'/'+service.icon+"/?sc=true&cache=1'></img>"
        +"<div class='info'><a>"
        +service.name+"</a><p>"+service.address+"</p></div>"
        +"</div>");
    }
  });
}
function RemoveFromArray(list,ele){
   var i = 0;
   for(;i<list.length;i++){
     if(list[i] == ele){
        break;
     }
   }
   if(i<list.length){
      list.splice(i,1);
   }
}
function RefreshServicesInRightDock(groups){
  if(zoyoe.has_right_dock == false){return;/* Ugly Code make sure we have right dock */}
  YUI().use('node',function(node){
    var eles = new Array();
    var limit = 13;
    var main_tag = true;
    for(var i=0;i<groups.length;i++){
      for(var j = 0;j<groups[i].service_list.length;j++){
        var service = groups[i].service_list[j];
        if(service.active){
          eles.push(groups[i].service_list[j]);
          service.in_square = true;
        }
      }
    }
    node.all('#right-bar-dock div.cicon').each(function(n){
      var service = node.Node.getDOMNode(n).service;
      if(service){
        if(service.in_square){
          limit -= 1;
          main_tag = false;
          RemoveFromArray(eles,service);
        }else{
          node.Node.getDOMNode(n).service = null;
          zoyoe.async_queue.pause(); 
          zoyoe.fade_list.push(n);
          zoyoe.async_queue.run(); 
        }
      }
    });
    var gicon = node.one('#right-bar-dock div.lane div.icon');
    var gservice = node.Node.getDOMNode(gicon).service;
    if(gservice && gservice.in_square){
      limit -= 1;
      RemoveFromArray(eles,gservice);
    }else{
      main_tag = true;
    }
    for(var i=0;limit > 0&&i<eles.length;i++){
      var service = eles[i];
      if(service.active){
        ShowServiceInRightDock(service,zoyoe.dock_style,main_tag);
        limit -= 1;
        main_tag = false;
      }
    }
  });
}

function SwitchPanel(h){
  YUI().use('node',function(node){
    if(h.shrink){
      h.innerHTML = "&#9666";
      var n = node.one('#config-bar');
      n.setStyle('width',"260px");
      n.setStyle('height',"");
      var m = node.one('#config-bar .window-title');
      m.setStyle('width','260px');
      var dummy = node.one('#config-bar .dummy');
      dummy.setStyle('display','none');
      h.shrink = false;
    }else{
      h.innerHTML = "&#9656";
      var n = node.one('#config-bar');
      n.setStyle('width',"100px");
      n.setStyle('height',"20px");
      var m = node.one('#config-bar .window-title');
      m.setStyle('width',"80px");
      var dummy = node.one('#config-bar .dummy');
      dummy.setStyle('display','block');
      h.shrink = true;
    }
  });
}


/*
 * Dialog Function Wrapper
 */
  function ShowAddServiceDialog(){
    var dialog_uri = "/adult/core/dialog/addservice/";
    zoyoe.InfoCollectDialog("AddService",dialog_uri,"form-addservice",AddService);
  }
  function ShowModifyServiceDialog(){
    var dialog_uri = "/adult/core/dialog/mdyservice/";
    zoyoe.InfoCollectDialog("ModifyBasicInfo",dialog_uri,"form-mdyservice",ModifyService);
  }
  function ShowAddGirlDialog(){
    var dialog_uri = "/adult/core/dialog/addgirl/"+zoyoe.service_name;
    zoyoe.InfoCollectDialog("AddGirl",
        dialog_uri,"form-addgirl",
        function(form_obj){
            zoyoe.comps['GIRLS'].AddGirl(form_obj);
        });
  }
  function ShowRegisterDialog(){
    dialog_uri = "/adult/core/dialog/register/";
    zoyoe.InfoCollectDialog("Register",
        dialog_uri,"form-register",Register);
  }
  function ShowLoginDialog(){
    var dialog_uri = "/adult/core/dialog/login/";
    zoyoe.InfoCollectDialog("Login",
        dialog_uri,"form-login",Login);
  }

/*
 * Component
 */

function Select(cname,info,html_ele){
  if(zoyoe.comps[cname]){
    var comp = zoyoe.comps[cname];
    comp.Select(info,html_ele);
  } 
}
